package com.atguigu.tingshu.payment.context;

import com.atguigu.tingshu.payment.strategy.PaymentStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author  王东剑
 * Created on 25/6/2024 PM5:37
 * Package_name com.atguigu.tingshu.payment.context
 * Description
 */
@Component
public class PaymentStrategyContext implements ApplicationContextAware {
	private static final Map<String, PaymentStrategy> PAYMENT_STRATEGY_MAP = new ConcurrentHashMap<>();

	public static PaymentStrategy getPaymentStrategy(String paymentType){
		return PAYMENT_STRATEGY_MAP.get(paymentType);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		Map<String, PaymentStrategy> beansOfType = applicationContext.getBeansOfType(PaymentStrategy.class);
		beansOfType.values().forEach(paymentStrategy -> PAYMENT_STRATEGY_MAP.put(paymentStrategy.getPaymentType(), paymentStrategy));
	}
}
